﻿// Open Source: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Project: YoProgramo.NET (http://code.google.com/p/yoprogramo/)
// Autor: Fabian Figueredo (info@fabianfigueredo.com.ar)
// Blog: blog.yoprogramo.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Validator.Engine;
using YoProgramo.Domain.BusinessLogic.Extensions;
using YoProgramo.Domain.Core.Entities;
using YoProgramo.Domain.Core.Interfaces;
using YoProgramo.Infrastructure.Tools.NHValidator;

namespace YoProgramo.Domain.BusinessLogic.Service
{
    public class CategoryService : ICategoryService {
        private ICategoryRepository _CategoryRepository;

        public CategoryService(ICategoryRepository c)
        {
            _CategoryRepository = c;
        }

        #region ICategoryService Members

        public IList<ICategory> GetAll() {
            return _CategoryRepository.GetAll();
        }

        public InvalidValue[] Create(ICategory obj) {
            InvalidValue[] validatorErrors = new NHValidatorWrapper<Category>().Validate((Category)obj);

            if (validatorErrors.Count() < 1)
                _CategoryRepository.SaveOrUpdate(obj);

            return validatorErrors;
        }

        public InvalidValue[] Create(string name) {
            ICategory c = new Category();
            c.Name = name;
            c.Slug = ExtraTools.GenerateSlug(name);
            return Create(c);
        }

        public InvalidValue[] Create(string name, string slug) {
            ICategory c = new Category();
            c.Name = name;
            c.Slug = slug;
            return Create(c);
        }

        public bool Update(ICategory obj) {
            try {
                InvalidValue[] validatorErrors = new NHValidatorWrapper<Category>().Validate((Category)obj);

                if (validatorErrors.Count() < 1)
                    _CategoryRepository.SaveOrUpdate(obj);

                return true;
            } catch {
                return false;
            }
        }

        public void Delete(ICategory obj) {
            _CategoryRepository.Delete(obj);
        }


        public ICategory GetByName(string name) {
            return GetAll().FirstOrDefault(w => w.Name == name);
        }


        public ICategory GetBySlug(string slug) {
            return GetAll().FirstOrDefault(w => w.Slug == slug);
        }

        #endregion
    }
}